import {
  getUploadSign
} from '@/api/sys/file'
import {getToken} from "@/utils/auth"

export default{
  data() {
    return {
      loading: false,
      progress: 0,
      isVideo: false
    }
  },
  methods: {
    /**
     * @method multiplePath 上传文件
     * @param {*} e 文件对象
     * @param {*} acl 是否返回永久地址
     * @param {*} ismultiple 是否为工作室荣誉图
     */
    inputChange(e, ismultiple) {
      const file = this.files = e.target.files[0]
      const originName = file.name;
      this.isVideo = file.type === 'video/mp4'
      this.$emit('file', e.target.files[0])
      if (file.size > 1024 * 1024 * 100) {
        this.$message({
          message: '文件超过10M',
          type: 'error',
          duration: 5 * 1000
        })
        return false
      }
      this.loading = true
  
      const fd = new FormData()
      const saveName = `${file.name.replace(/[\+\-\s]/gi, '')}`
      fd.append('file', file, saveName)
      fd.append("name",originName)

      const xhr = new XMLHttpRequest()
      xhr.open('post', "/admin/file/upload", true)
      xhr.setRequestHeader("token",getToken())
      // 上传进度回调
      xhr.upload.addEventListener('progress', (evt) => {
        this.progress = Math.round((evt.loaded) * 100 / evt.total)
      }, false)
      // 上传完成回调
      xhr.addEventListener('load', (e) => {
        if (e.target.status !== 200) {
          this.progress = 100
          this.$message({
            message: '上传失败',
            type: 'error',
            duration: 5 * 1000
          })
          this.error = true
          this.loading = false
        } else {
          const res = JSON.parse(e.target.response)
          if (res.code > 0) {
            this.progress = 100
            this.$message({
              message: '上传失败',
              type: 'error',
              duration: 5 * 1000
            })
            this.error = true
            this.loading = false
          } else {
            setTimeout(() => {
              this.progress = 0
            }, 2000)
            this.name = saveName
            this.fileId = res.id
            this.filename = res.filename
            this.error = false
            ismultiple ? this.multiplePath = res.url : this.fileUrl = res.url
            this.loading = false          
            if(this.uploadSuccess){
              this.uploadSuccess(res)
            }
          }
        }
      }, false)
      // 发送请求
      xhr.send(fd)      
    },
    handleClick() {
      if (this.loading) return
      this.$refs.uploaderInput.value = null
      this.$refs.uploaderInput.click()
    }
  }
}
